package cn.tedu.tvrd.filter;

import cn.tedu.tvrd.entity.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

//告诉编译器这个类是一个过滤器
@WebFilter(filterName = "MyFilter",urlPatterns = {"/send.html","/admin.html"})
public class MyFilter implements Filter {
    //当过滤器销毁时执行
    public void destroy() {
    }
    //当客户端请求资源时执行
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //判断当前客户端是否登录过 登录过放行,否则拦截
        //将父类型转成子类型, 因为用到的方法是子类型中的方法
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //得到Session对象
        HttpSession session = request.getSession();
        //从Session中判断是否有user对象
        User user = (User) session.getAttribute("user");
        if (user!=null){//登录过
            chain.doFilter(req, resp);//放行
        }else{//没登录过
            response.sendRedirect("/login.html");//重定向到登录页面
        }
    }
    //当过滤器初始化时执行
    public void init(FilterConfig config) throws ServletException {

    }

}
